/**
 * ReportGear(2011)
 */
package com.reportgear.report.print;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.print.PageFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;

import net.abbp.report.context.ReportContext;
import net.abbp.report.model.ReportModel;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.abbp.core.util.StringUtils;
import com.reportgear.report.model.calculator.CalculatorHelper;

/**
 * 打印预览
 * 
 * @version 1.0 2011-4-13
 * @author <a herf="lexloo@gmail.com">lexloo</a>
 * @since Report 1.0
 */
public class PreviewPane extends JPanel {

    private static final Logger logger = LoggerFactory.getLogger(PreviewPane.class.getName());
    // 显示页面数
    private int showPageCount = 1;
    private PageFormat pageFormat = new PageFormat();
    private JButton nextButton;
    private JButton previousButton;
    // private JButton pagesetupButton;
//    private JButton printButton;
    private JButton closeButton;

    // 内部预览页面
    private InnerPreviewPane innerPreviewPane;
    // 报表模型
    private ReportModel currentReport;
    // 报表列表
    private Iterator<ReportPage> reportPageIterator = null;
    // 报表页面列表
    private List<ReportPage> reportPageList = new ArrayList<ReportPage>();
    // 当前页指针
    private int currentIndex = 0;

    // 显示下一页
    private ActionListener nextActionListener = new ActionListener() {

        public void actionPerformed(ActionEvent evt) {
            showNextPage();
        }
    };
    // 显示前一页
    private ActionListener previousActionListener = new ActionListener() {

        public void actionPerformed(ActionEvent evt) {
            showPreviousPage();
        }
    };
    // // 页面设置
    // private ActionListener pageSetupActionListener = new ActionListener() {
    //
    // public void actionPerformed(ActionEvent evt) {
    // // PageSetupDialog pageSetupDialog =
    // //
    // PageSetupDialog.showWindow(SwingUtilities.getWindowAncestor(PreviewPane.this));
    // // pageSetupDialog.populate(PreviewPane.this.currentReport);
    // // pageSetupDialog.setVisible(true);
    // // int i = pageSetupDialog.getReturnValue();
    // // if (i != 0) {
    // // return;
    // // }
    // // pageSetupDialog.update(PreviewPane.this.currentReport);
    // // pageSetupDialog.update(PreviewPane.this.backupReport);
    // // ReportHelper.clearFormulaResult(PreviewPane.this.currentReport);
    // //
    // PreviewPane.this.print(PreviewPane.this.currentReport.execute(PreviewPane.this.parameterMap).generateReportPageIterator());
    // }
    // };
    // 打印
    private ActionListener printActionListener = new ActionListener() {

        public void actionPerformed(ActionEvent evt) {
            List<ReportPage> pages = new ArrayList<ReportPage>();
            Iterator<ReportPage> rs = new ReportPageIterator(currentReport);
            while (rs.hasNext()) {
                pages.add(rs.next());
            }
            new Printer().print(pages);
        }
    };

    // // 打印设置
    // private ActionListener printSetupActionListener = new ActionListener() {
    //
    // public void actionPerformed(ActionEvent paramActionEvent) {
    // PrintService printService = null;
    // if (printService == null) {
    // printService = PrintServiceLookup.lookupDefaultPrintService();
    // }
    // PrinterJob printerJob = PrinterJob.getPrinterJob();
    // try {
    // printerJob.setPrintService(printService);
    // } catch (PrinterException ex) {
    // logger.warn(ex.getMessage());
    // }
    // ReportSettings reportSettings =
    // PreviewPane.this.currentReport.getReportSettings();
    // PaperSetting paperSetting = reportSettings.getPaperSetting();
    //
    // int orientation = paperSetting.getOrientation();
    // PaperSize paperSize = paperSetting.getPaperSize();
    // Margin margin = paperSetting.getMargin();
    // Paper paper = PreviewPane.this.pageFormat.getPaper();
    //
    // paper.setSize(paperSize.getWidth(), paperSize.getHeight());
    // paper.setImageableArea(margin.getLeft(), margin.getTop(),
    // paperSize.getWidth() - (margin.getLeft())
    // - (margin.getRight()), paperSize.getHeight() - (margin.getTop()) -
    // (margin.getBottom()));
    //
    // PreviewPane.this.pageFormat.setPaper(paper);
    //
    // PreviewPane.this.pageFormat.setOrientation(orientation);
    //
    // printerJob.pageDialog(PreviewPane.this.pageFormat);
    // paper = PreviewPane.this.pageFormat.getPaper();
    // paper.setImageableArea(0.0D, 0.0D, paper.getWidth(), paper.getHeight());
    // PreviewPane.this.pageFormat.setPaper(paper);
    // }
    // };

    /**
     * 预览页面构造函数
     */
    public PreviewPane() {
        this.setLayout(new BorderLayout());

        JPanel toolPane = new JPanel();
        this.add(toolPane, BorderLayout.NORTH);
        toolPane.setLayout(new FlowLayout(FlowLayout.LEFT, 4, 2));

        this.previousButton = new JButton("上一页");
        toolPane.add(this.previousButton);
        this.previousButton.setMnemonic('V');
        this.previousButton.addActionListener(this.previousActionListener);

        this.nextButton = new JButton("下一页");
        toolPane.add(this.nextButton);
        this.nextButton.setMnemonic('N');
        this.nextButton.addActionListener(this.nextActionListener);

        // this.pagesetupButton = new JButton("纸张设置");
        // toolPane.add(this.pagesetupButton);
        // this.pagesetupButton.setMnemonic('S');
        // this.pagesetupButton.addActionListener(this.pageSetupActionListener);

//        this.printButton = new JButton("打印");
//        toolPane.add(this.printButton);
//        this.printButton.setMnemonic('P');
//        this.printButton.addActionListener(this.printActionListener);

        this.closeButton = new JButton("关闭");
        toolPane.add(this.closeButton);
        this.closeButton.setMnemonic('E');
        this.closeButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent evt) {
                Object src = evt.getSource();
                if (src instanceof JComponent) {
                    JComponent c = (JComponent) src;

                    Window w = SwingUtilities.getWindowAncestor(c);
                    w.dispose();
                }
            }
        });

        this.innerPreviewPane = new InnerPreviewPane();
        this.add(new JScrollPane(this.innerPreviewPane), BorderLayout.CENTER);
    }

    /**
     * 获取显示页面数
     * 
     * @return 显示页面数
     */
    public int getShowPageCount() {
        return this.showPageCount;
    }

    /**
     * 设置显示页面数
     * 
     * @param showPageCount
     *            显示页面数据
     */
    public void setShowPageCount(int showPageCount) {
        this.showPageCount = showPageCount;
    }

    /**
     * 设置按钮的状态
     */
    private void checkButtonEnabled() {
        this.previousButton.setEnabled(false);
        this.nextButton.setEnabled(false);
//        this.printButton.setEnabled(false);
        // this.printSetupButton.setEnabled(false);
        if (this.currentIndex > this.showPageCount) {
            this.previousButton.setEnabled(true);
        }
        if (this.currentIndex < this.reportPageList.size()) {
            this.nextButton.setEnabled(true);
        }
        // if (this.currentReport != null) {
        // this.pagesetupButton.setEnabled(true);
        // } else {
        // this.pagesetupButton.setEnabled(false);
        // }
        if (this.reportPageList.size() <= 0) {
            return;
        }
//        this.printButton.setEnabled(true);
        // this.printSetupButton.setEnabled(true);
    }

    /**
     * 显示前一页
     */
    private void showPreviousPage() {
        if (this.currentIndex <= this.showPageCount) {
            return;
        }
        this.currentIndex -= this.showPageCount;
        ReportPage[] pageArr = new ReportPage[Math.min(this.showPageCount, this.reportPageList.size()
                - this.currentIndex)];
        for (int i = 0; i < pageArr.length; i++) {
            pageArr[i] = this.reportPageList.get(i + this.currentIndex - this.showPageCount);
        }
        this.innerPreviewPane.print(pageArr);
        checkButtonEnabled();
    }

    /**
     * 显示下一页
     */
    private void showNextPage() {
        for (int i = 0; (i < this.showPageCount + 1) && (this.reportPageIterator.hasNext()); i++) {
            this.reportPageList.add(this.reportPageIterator.next());
        }

        if (this.reportPageList.isEmpty()) {
            return;
        }

        ReportPage[] pageArr = new ReportPage[Math.min(this.showPageCount, this.reportPageList.size()
                - this.currentIndex)];

        for (int i = 0, len = pageArr.length; i < len; i++) {
            pageArr[i] = this.reportPageList.get(i + this.currentIndex);
        }

        this.currentIndex += this.showPageCount;
        this.innerPreviewPane.print(pageArr);

        checkButtonEnabled();
    }

    /**
     * 打印报表
     * 
     * @param model
     *            报表模型
     */
    public void print(ReportModel model) {
        // TODO 模型计算被注释了
        this.currentReport = CalculatorHelper.calResumeModel(model, StringUtils.convertToString(ReportContext.INSTANCE
                .getBusItem("PersonId"), "0"));

        print(new ReportPageIterator(this.currentReport));
    }

    /**
     * 打印报表
     * 
     * @param pageList
     */
    public void print(List<ReportPage> pageList) {
        print(pageList.iterator());
    }

    public void print(Iterator<ReportPage> iterator) {
        this.reportPageIterator = iterator;
        this.currentIndex = 0;
        this.reportPageList.clear();
        this.innerPreviewPane.print((ReportPage) null);
        checkButtonEnabled();
        showNextPage();
    }
}